//控制置信度滑条和显示值的绑定
let slider_conf = document.getElementById('conf');
let slider_conf_value = document.getElementById('conf_value');

slider_conf.addEventListener("input", () => {
    slider_conf_value.value = slider_conf.value;
});

slider_conf_value.addEventListener("input", () => {
    value = slider_conf_value.value
    value = value.replace(/[^\d]/g, '')
    console.log(value);
    value = value > 100 ? value = 100 : value === "" ? value = 0 : value;

    slider_conf.value = value;
    slider_conf_value.value = value;
});


// let slider_line_width = document.getElementById('line_width');
// let slider_line_width_value = document.getElementById('line_width_value');

// slider_line_width.addEventListener("input", ()=>{
//     slider_line_width_value.innerHTML = "线宽:"+slider_line_width.value   
// });

// 代码来自https://github.com/ imfing/keras-flask-deploy-webapp?tab=readme-ov-file项目
let file_select = document.getElementById('file_upload');
let file_drag = document.getElementById('file_drag');
// 拖拽事件监听
file_drag.addEventListener('dragover', fileDragHover, false)
file_drag.addEventListener('dragleave', fileDragHover, false)
file_drag.addEventListener('drop', fileSelectHandler, false)
// 文件上传事件监听
file_select.addEventListener('change', fileSelectHandler, false)

function fileDragHover(e) {
    // prevent default.conf behaviour
    e.preventDefault();
    e.stopPropagation();

    file_drag.className = e.type === "dragover" ? "upload_box dragover" : "upload_box";
}

function fileSelectHandler(e) {
    // handle file selecting
    var files = e.target.files || e.dataTransfer.files;
    fileDragHover(e);
    for (var i = 0, f; (f = files[i]); i++) {
        previewFile(f);
    }
}

//========================================================================
// Web page elements for functions to use
//========================================================================

var imagePreview = document.getElementById("image_preview");
var uploadCaption = document.getElementById("upload_caption");
var imageDetect = document.getElementById("image_detect");
var imageSegment = document.getElementById("image_segment");
// var imageOriented = document.getElementById("image_oriented");
var imagePose = document.getElementById("image_pose");
var imageBoxTitle = document.getElementsByClassName("image_box_title");
// var predResult = document.getElementById("pred_result");
var loader = document.getElementsByClassName("loader");
var imageDisplay = document.getElementsByClassName("image_display")

//========================================================================
// Main button events
//========================================================================

function submitImage() {
    // action for the submit button
    console.log("submit");
    if (!imagePreview.src || !imagePreview.src.startsWith("data")) {
        window.alert("在提交之前选择图片")
        return
    }
    // 为loader里的所有元素移除hidden类名
    // 作用：显示svg图片动画
    for (let loaderElement of loader) {
        loaderElement.classList.remove("hidden")
    }
    // 为imageDisplay里所有的元素添加loading类名
    // 作用：让图片亮度降低至30%
    for (let imageDisplayElement of imageDisplay) {
        imageDisplayElement.classList.add("loading")
    }
    let img_size = imagePreview.src.length * 3 / 4 / 1048576
    console.log("图片大小:" + img_size)
    // if (img_size > 15)
    //     window.alert("图片太大，请选择小于10M的图片")
    // else
    predictImage(imagePreview.src)
}

function clearImage() {
    imagePreview.src = "";
    imageDetect.src = "";
    imageSegment.src = "";
    // imageOriented.src = "";
    imagePose.src = "";
    file_select.value = "";
    slider_conf.value = 25
    slider_conf_value.value = 25
    hide(imagePreview);
    hide(imageDetect);
    hide(imageSegment);
    // hide(imageOriented);
    hide(imagePose);
    for (i of imageBoxTitle) {
        hide(i)
    }
    for (let imageDisplayElement of imageDisplay) {
        imageDisplayElement.classList.remove("loading")
    }
    for (let loaderElement of loader) {
        loaderElement.classList.add("hidden")
    }
    show(uploadCaption);
}

function previewFile(file) {
    // show the preview of the image
    console.log(file.name);

    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {

        show(imagePreview);
        hide(uploadCaption);

        for (let imageBoxTitleElement of imageBoxTitle) {
            imageBoxTitleElement.classList.remove("hidden")
        }
        displayImage(reader.result, imagePreview.id);
        displayImage(reader.result, imageDetect.id);
        displayImage(reader.result, imageSegment.id);
        displayImage(reader.result, imagePose.id);
    };
}

//========================================================================
// Helper functions
//========================================================================

function predictImage(image) {
    data = {
        image: image,
        conf: slider_conf_value.value
    };
    fetch("/predict", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    }).then(res => {
        if (res.ok) {
            console.log("请求成功")
            res.json().then(async data => {
                console.log("数据接收成功")
                for (let datum of data) {
                    console.log(datum.name+"大小:"+datum.image.length* 3 / 4 / 1048576)
                    await displayImage(datum.image, "image_" + datum.name)
                }
                for (let loaderElement of loader) {
                    loaderElement.classList.add("hidden")
                }
                for (let imageDisplayElement of imageDisplay) {
                    imageDisplayElement.classList.remove("loading")
                }
            })
        } else {
            res.json().then(data => {
                console.log("发生错误", data.error)
                window.alert("出现错误:" + data.error)
            })
        }
    }).catch(err => {
        console.log("发生错误", err.message)
        alert("出现错误\n" + err.message)
    })
}

function displayImage(image, id) {
    // display image on given id <img> element
    let display = document.getElementById(id);
    display.src = image;
    show(display);
}

function hide(el) {
    // hide an element
    el.classList.add("hidden");
}

function show(el) {
    // show an element
    el.classList.remove("hidden");
}